package com.emuporium.gymrat.android.exercises;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.emuporium.gymrat.android.R;
import com.emuporium.gymrat.android.database.DatabaseExerciseAdapter;

public class ExercisesDetails extends Activity {
	Cursor cExercise;
	Cursor cVariations;
	Cursor cEquipment;
	Cursor cFreeVariations;
	Cursor cFreeEquipment;
	SimpleCursorAdapter exerciseAdapter;
	DatabaseExerciseAdapter db;
	int exerciseId;
	Dialog varDialog;
	RelativeLayout layout;
	LinearLayout variationList;
	LinearLayout equipmentList;

	TextView title;
	TextView group;
	boolean isCustom = false;

	// Button addVariation = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exercises_details);

		exerciseId = getIntent().getIntExtra("gymrat.id", 0);

		layout = (RelativeLayout) findViewById(R.id.exercises_details_layout);
		title = (TextView) findViewById(R.id.exercises_details_name);
		group = (TextView) findViewById(R.id.exercises_details_group);
		variationList = (LinearLayout) findViewById(R.id.exercises_details_variations_list);
		equipmentList = (LinearLayout) findViewById(R.id.exercises_details_equipment_list);

	}

	/**
	 * Show dialog to prompt user to change muscle group
	 */
	public void promptRegroup() {
		final Dialog dialog = new Dialog(this);
		ListView listView = new ListView(this);
		Button cancel = new Button(this);
		cancel.setText("Cancel");
		final Cursor cGroup = db.getMuscleGroups();
		// startManagingCursor(cGroup);
		SimpleCursorAdapter a = new SimpleCursorAdapter(ExercisesDetails.this,
				android.R.layout.simple_list_item_1, cGroup,
				new String[] { "name" }, new int[] { android.R.id.text1 });
		listView.addFooterView(cancel);
		listView.setAdapter(a);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView adapter, View v, int pos,
					long row) {
				cGroup.moveToPosition(pos);
				db.changeMuscleGroup(exerciseId, cGroup.getInt(0));
				group.setText(cGroup.getString(1));
				dialog.dismiss();
			}
		});
		dialog.setContentView(listView);
		dialog.setTitle("Change Muscle Group");

		cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				cGroup.close();
			}
		});

		dialog.show();

	}

	/**
	 * Show dialog to prompt user to rename exercise
	 */
	public void promptRename() {
		final Dialog dialog = new Dialog(this);
		LinearLayout promptLayout = new LinearLayout(this);
		final EditText edit = new EditText(this);
		edit.setHint(title.getText());
		edit.setText(title.getText());
		Button submit = new Button(this);
		submit.setText("Save");
		Button cancel = new Button(this);
		cancel.setText("Cancel");

		submit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (db.renameExercise(exerciseId, edit.getText().toString()))
					title.setText(edit.getText());
				dialog.dismiss();
			}
		});

		cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		promptLayout.addView(edit);
		promptLayout.addView(submit);
		promptLayout.addView(cancel);
		dialog.setContentView(promptLayout);
		dialog.setTitle("Rename " + title.getText());
		dialog.show();
	}

	/**
	 * Clear the LinearLayout used to list the equipment and add them again.
	 * This is called whenever an item is added or removed.
	 */
	public void updateEquipment() {
		cEquipment = db.getExerciseEquipment(exerciseId);
		// startManagingCursor(cEquipment);
		equipmentList.removeAllViews();
		while (cEquipment.moveToNext()) {
			TextView equipment = new TextView(this);
			equipment.setId(cEquipment.getInt(0));
			equipment.setText(cEquipment.getString(1));
			equipment.setTextSize(20);
			equipment.setFocusable(true);
			equipment.setFocusableInTouchMode(true);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			lp.gravity = Gravity.RIGHT;

			if (isCustom) {
				equipment
						.setOnLongClickListener(new View.OnLongClickListener() {
							public boolean onLongClick(View v) {
								Toast.makeText(ExercisesDetails.this,
										((TextView) v).getText() + " Removed",
										Toast.LENGTH_SHORT).show();
								db.removeEquipmentFromExercise(exerciseId, v
										.getId());
								updateEquipment();
								return true;
							}
						});
			}
			equipmentList.addView(equipment, lp);
		}

		// If the exercise for this activity is custom created by the user,
		// allow them to alter its variations
		if (isCustom) {
			Button addEquipment = new Button(this);
			addEquipment.setText("Add Equipment");
			addEquipment.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					cFreeEquipment = db.getUnusedEquipment(exerciseId);
					 startManagingCursor(cFreeEquipment);
					varDialog = new Dialog(ExercisesDetails.this);

					ListView listView = new ListView(ExercisesDetails.this);

					SimpleCursorAdapter adapter = new SimpleCursorAdapter(
							ExercisesDetails.this,
							android.R.layout.simple_list_item_1,
							cFreeEquipment, new String[] { "name" },
							new int[] { android.R.id.text1 });
					listView.setAdapter(adapter);
					listView.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView av, View v,
								int pos, long id) {

							cFreeEquipment.moveToPosition(pos);
							db.addEquipmentToExercise(exerciseId,
									cFreeEquipment.getInt(0));
							varDialog.dismiss();
							updateEquipment();
							cFreeEquipment.close();
						}
					});
					varDialog.setContentView(listView);
					varDialog.setTitle("Select Equipment");
					varDialog.show();
				}
			});
			equipmentList.addView(addEquipment);
		}
		cEquipment.close();
	}

	/**
	 * Clear the LinearLayout used to list the variations and add them again.
	 * This is called whenever an item is added or removed.
	 */
	public void updateVariations() {
		cVariations = db.getExerciseVariations(exerciseId);
		// startManagingCursor(cVariations);
		variationList.removeAllViews();
		while (cVariations.moveToNext()) {
			TextView variation = new TextView(this);
			variation.setId(cVariations.getInt(0));
			variation.setText(cVariations.getString(1));
			variation.setTextSize(20);
			variation.setFocusable(true);
			variation.setFocusableInTouchMode(true);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			lp.gravity = Gravity.RIGHT;

			// If the exercise is custom created, allow user to long click items
			// to remove
			if (isCustom) {
				variation
						.setOnLongClickListener(new View.OnLongClickListener() {
							public boolean onLongClick(View v) {
								Toast.makeText(ExercisesDetails.this,
										((TextView) v).getText() + " Removed",
										Toast.LENGTH_SHORT).show();
								db.removeVariationFromExercise(exerciseId, v
										.getId());
								updateVariations();
								return true;
							}
						});
			}
			variationList.addView(variation, lp);
		}

		// If the exercise for this activity is custom created by the user,
		// allow them to add new variations
		if (isCustom) {
			Button addVariation = new Button(this);
			addVariation.setText("Add Variation");
			addVariation.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					cFreeVariations = db.getUnusedVariations(exerciseId);
					 startManagingCursor(cFreeVariations);
					varDialog = new Dialog(ExercisesDetails.this);

					ListView listView = new ListView(ExercisesDetails.this);
					Button addNew = new Button(ExercisesDetails.this);
					addNew.setText("Create New");
					listView.addFooterView(addNew);
					SimpleCursorAdapter adapter = new SimpleCursorAdapter(
							ExercisesDetails.this,
							android.R.layout.simple_list_item_1,
							cFreeVariations, new String[] { "name" },
							new int[] { android.R.id.text1 });
					listView.setAdapter(adapter);
					
					listView.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView av, View v,
								int pos, long id) {

							cFreeVariations.moveToPosition(pos);
							db.addVariationToExercise(exerciseId,
									cFreeVariations.getInt(0));
							varDialog.dismiss();
							updateVariations();
							cFreeVariations.close();
						}
					});
					varDialog.setContentView(listView);
					varDialog.setTitle("Select a Variation");
					varDialog.show();
				}
			});
			variationList.addView(addVariation);
		}
		cVariations.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.exercises_details, menu);
		if (!isCustom) {
			menu.removeItem(R.id.exercises_details_menu_rename);
			menu.removeItem(R.id.exercises_details_menu_regroup);
			menu.removeItem(R.id.exercises_details_menu_delete);
		}
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exercises_details_menu_rename:
			promptRename();
			break;

		case R.id.exercises_details_menu_regroup:
			promptRegroup();
			break;

		case R.id.exercises_details_menu_delete:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"Are you sure you want to delete " + title.getText() + "?")
					.setCancelable(true).setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									ExercisesDetails.this.finish();
								}
							}).setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		super.onResume();
		db = new DatabaseExerciseAdapter(this);
		db.open();
		cExercise = db.getExercise(exerciseId);
		// startManagingCursor(cExercise);

		if (cExercise.moveToFirst()) {
			title.setText(cExercise.getString(1));
			group.setText(cExercise.getString(2));
			if (cExercise.getInt(3) == 1) {
				isCustom = true;
				findViewById(R.id.exercises_details_variations_custom)
						.setVisibility(View.VISIBLE);
				findViewById(R.id.exercises_details_equipment_custom)
						.setVisibility(View.VISIBLE);
				title.setOnLongClickListener(new View.OnLongClickListener() {
					public boolean onLongClick(View v) {
						promptRename();

						return true;
					}
				});

				group.setOnLongClickListener(new View.OnLongClickListener() {
					public boolean onLongClick(View v) {
						promptRegroup();

						return true;
					}
				});

			}
		}
		updateVariations();
		updateEquipment();
	}

	@Override
	public void onPause() {
		super.onPause();
		cExercise.close();
		// cVariations.close();
		// cEquipment.close();
		// cFreeVariations.close();
		// cFreeEquipment.close();
		db.close();
	}
}
